/**
 * 物料样式模板
 */
define(['../../common/service', 'masonry', 'imagesloaded', 'language'],
    function (http, Masonry, Img, I18N) {
        var materialTemplates = {
            param: {
                pSize: 20,
                cPage: 1,
                creativeStatus: [],
                categoryList: [],
                name: "",
                tagId: 0,
                type: 1, // drop name:1; tag 2
                order: 1
            },
            timeObj: null,
            init: function () {
                var _this = this;
                var $grid = _this.initMasonry();
                //_this.initDrop($grid);
                _this.initSearch($grid);
                _this.showList($grid, _this.param, true);
                _this.scrollEvnet($grid, _this.param);
                _this.initSearchAndSortEvent($grid);
                // filter
                _this.initFilter();
                _this.filterBtnEvent($grid);
                _this.events();
                _this.initTreeDrop();
            },
            initMasonry: function () {
                $.bridget('masonry', Masonry, $);
                var $grid = $('.grid').masonry({
                    itemSelector: '.grid-item',
                    percentPosition: true,
                    columnWidth: '.grid-sizer'
                });
                $('.grid').imagesLoaded().progress(function () {
                    $grid.masonry('layout');
                });
                return $grid;
            },
            getSearchParam: function () {
                var _this = this;
                var tempParam = $.extend({}, _this.param);
                //add search param
                if ($('input[name=name-tag]').attr("data-val") == "1") {
                    tempParam.type = 1;
                    tempParam.name = $('input[name=name-search1]').val();
                } else {
                    tempParam.type = 2;
                    tempParam.tagId = $('div[name=picTemplateSearch2] input').attr('cid');
                }
                //add order param
                tempParam.order = $('.searchDiv').attr("data-order");
                //add filter param
                var creativeStatus = [],
                    categoryArr = [],
                    categoryList = {creativeType: [], adPlaceMent: [], adTarget: [], adCarousel: [], adLink: []};
                //获取tag
                var tags = _this.getFilterData();
                $.each(tags, function (i, o) {
                    if (o.flag == 0) {
                        creativeStatus.push(o.type);
                    } else {
                        if (o.type == "creativeType") {
                            categoryList.creativeType.push(Number(o.id));
                        } else if (o.type == "adPlaceMent") {
                            categoryList.adPlaceMent.push(Number(o.id));
                        } else if (o.type == "adTarget" || o.type == "festival") {
                            categoryList.adTarget.push(Number(o.id));
                        } else if (o.type == "adCarousel") {
                            categoryList.adCarousel.push(Number(o.id));
                        } else if (o.type == "adLink") {
                            categoryList.adLink.push(Number(o.id));
                        }else if (o.type == "productFeed") {
                            tempParam.feedId = o.id;
                        }
                    }
                });
                categoryArr.push(categoryList);
                tempParam.creativeStatus = creativeStatus;
                tempParam.categoryList = categoryArr;
                return tempParam;
            },
            /**
             * 使用瀑布流加载显示模板列表
             * @param $grid
             * @param param
             * @param flag
             * @returns {boolean}
             */
            showList: function ($grid, param, flag) {
                var _this = this;
                if (!_this.checkUrl()) {
                    return false;
                }
                if (flag) {
                    $('#masonryDom').empty();
                }
                http.work('/ecTemplateMateriel/findPager', param, 'POST').then(function (res) {
                    if (res.flag == 'fail') {
                        Kit.alert2(res.errorMsg);
                        return;
                    } else {
                        if (res.data.ecTemplateMateriels.length == 0) {
                            if (flag) {
                                $('.temp-total>span').html(0);
                            }
                            $('.masonryDom-finish').show();
                            setTimeout(function () {
                                $('.masonryDom-finish').hide();
                            }, 3000);
                            //如果没有数据，清除滚动条事件
                            $(".fmp-article").unbind("scroll");
                            return;
                        }
                        var _html = "";
                        //显示总数
                        $('.temp-total>span').html(res.data.paginator.tSize);
                        $.each(res.data.ecTemplateMateriels, function (i, obj) {
                            var picData = obj.materiel;
                            var ext = obj.ext;
                            var _picBackground = ""
                            var tempObj = _this.checkIsNotSinglePicture(_html, _picBackground, picData);
                            _html += tempObj.h;
                            _picBackground += tempObj.p;
                            _html += '<img class="pic-main" src="' + picData.thumbnail + '"/>';
                            //添加说明和时间
                            _html += '<div class="pic-name" title="' + picData.name + '">' + picData.name + '</div>'
                            _html += '<div class="pic-time"><i class="font-icon font-icon-time"></i>'
                                + moment(picData.createTime).format("YYYY-MM-DD") + '</div>';
                            _html += _picBackground;
                            //显示  遮罩层
                            if (obj.process < 100) {//正在生成中
                                //判断是否失败！
                                if(picData.createdStatus == 3){
                                    //加入 判断条件 createdStatus  生成中1 生成成功2 失败 3  初始化 0
                                    _html += _this.showTemplateForFailure(picData,ext);
                                    _html += '</div>';
                                }else{
                                    _html = _this.showTemplateForGenerating(_html,obj);
                                }

                            } else {
                                //加入 遮罩层
                                //加入 状态图标
                                //加入 判断条件
                                //添加需求变更 1、修改投放中和暂停状态，开放编辑功能，但是只能编辑展示位置
                                //2、修改左边样式渲染。 3、选择展示之后需要在最右边一栏可以有预览标签。
                                // modify by hermen 2016-08-02

                                if (ext.running > 0) { //投放中  不可编辑和删除     //参考上面的注释
                                    _html = _this.showTempLateForRunning(_html,obj,picData,ext);
                                } else if (ext.paused > 0) { //暂停  不可编辑和删除
                                    _html = _this.showTemplateForPause(_html,obj,picData,ext);
                                    //开放编辑  只能编辑展示位置
                                } else if (ext.deleted > 0) { //停止投放 都可用
                                    _html = _this.showTemplateForDelete(_html,obj,picData,ext);
                                } else { //未使用
                                    _html = _this.showTemplateForNotUsed(_html,obj,picData,ext);
                                }
                            }
                            _html += '</div>'
                        });
                        $grid.append(_html).masonry('appended', $(_html));
                        // 渐显新的内容
                        $(_html).animate({opacity: 1});
                        //判断是否显示隐藏
                        //var showDom = $grid.find('pic-right').attr('data-show');
                        $.each($('#masonryDom').find('.pic-right'), function (i, obj) {
                            var $item = $(obj).parent();
                            if ($(obj).attr('data-show') == "false") {
                                //
                                $item.find('.pic-background').hide();
                                $item.find('.pic-background2').hide();
                                _this.mouseenterEvent($item);
                                _this.mouseleaveEvent($item);
                                //绑定 图片上的事件
                                _this.bindPicBtnEvent($item);
                            } else {
                                var _id = $item.attr('data-id');
                                //if(!$item.data("isProgress")){
                                //    $item.data("isProgress",true);
                                _this.keepOnSearchStatus($item, _id);
                                //}
                            }
                        });
                        //绑定 重新生成事件
                        _this.bindRebuildEvent();
                    }
                });
            },
            scrollEvnet: function ($grid, tempParam) {
                var _this = this;
                if (!_this.checkUrl()) {
                    return false;
                }
                // 初始化 sentIt
                var sentIt = true;
                var cPage = 1;
                var tempParam2 = $.extend({}, tempParam);
                $(".fmp-article").unbind("scroll").bind("scroll", function () {
                    if (!_this.checkUrl()) {
                        return false;
                    }
                    if ($(".fmp-article").scrollTop() > $('.container-fluid').height() - $(window).height() && sentIt) {
                        sentIt = false;
                        // 判断下一页链接是否为空
                        tempParam2.cPage = cPage + 1;
                        _this.showList($grid, tempParam2, false);
                        setTimeout(function () {
                            sentIt = true;
                            cPage++;
                        }, 2000);
                    }
                });
            },
            initDrop: function (s1, s2) {
                $("div.ndp-drop-wrapper[name=inline-drop]").drop({
                    data: [{id: 1, name: I18N.getText('materialTemplate', 'selectTagName')}, {
                        id: 2,
                        name: I18N.getText('materialTemplate', 'selectTagTags')
                    }],
                    name: "name-tag" //为了方便serialize 建议设置name 属性
                }).on("ITEM_CLICK", function (e) { //下拉选择项点击事件
                    //返回的数据有
                    if (e.originalEvent.data.val == "1") {
                        s2.hide();
                        $('input[name=name-search1]').val('');
                        s1.show();
                    } else {
                        s1.hide();
                        $('input[name=name-search2]').val('');
                        s2.show();
                    }
                }).val(I18N.getText('materialTemplate', 'selectTagName'));
                $("input[name=name-tag]").attr("data-val", "1");
            },
            initSearch: function ($grid) {
                var _this = this;
                var search1 = $(".ndp-search-wrapper[name=picTemplateSearch1]").search({
                    placeholder: I18N.getText('materialTemplate', 'selectTagSearch'),
                    name: "name-search1" //为了方便serialize 建议设置name 属性
                }).on("do_search", function (e) {
                    //用户输入内容，回车 或者点击搜索(放大镜) 触发这个事件
                    //清除tag
                    //$('.tags').empty();
                    var tempParam = _this.getSearchParam();
                    _this.showList($grid, tempParam, true);
                    _this.scrollEvnet($grid, tempParam);
                }).val(""); //设置input 显示的值;;
                var search2 = $(".ndp-search-wrapper[name=picTemplateSearch2]").search({
                    type: 3,
                    ajaxOptions: {
                        type: "GET",
                        url: cors_config.api_host + "/ecTemplateMateriel/queryTags",
                        xhrFields: {withCredentials: true}
                    },
                    name: "name-search2"
                }).on("do_search", function (e) {
                    //清除tag
                    //$('.tags').empty();
                    //用户输入内容，回车 或者点击搜索(放大镜) 触发这个事件
                    if (e.originalEvent.data.id == undefined && $.trim(e.originalEvent.data.text) != "") {
                        Kit.alert_info(I18N.getText('materialTemplate', 'selectCorrectTag'));
                    } else {
                        var tempParam = _this.getSearchParam();
                        _this.showList($grid, tempParam, true);
                        _this.scrollEvnet($grid, tempParam);
                    }
                }).on("INPUT_CLEAR", function (e) { //点击x 清除内容
                    //清除cid 值，因为现在只能在这里取他的值。真恶心。
                    $('div[name=picTemplateSearch2] input').removeAttr('cid');
                });
                search2.hide();
                _this.initDrop(search1, search2);
            },
            initSearchAndSortEvent: function ($grid) {
                var _this = this;
                $('.sort-filter').unbind('click').bind('click',function () {
                    $('#picList').hide();
                    $('#filter').removeClass("hidden"); //searchDiv
                    $('div.creatTempBtn-text').removeClass("hidden");
                    $('.searchDiv').hide();
                    $('div.creatTempBtn-btn').hide();
                    //显示箭头
                    $('#festivalImg').offset({left: $('label[for=festival-all]').offset().left + 20});
                    //记录下tags数，入股如果点击的是cancel，则全部还原
                    var values = [];
                    $('input[type=checkbox]:checked').each(function (i, obj) {
                        values.push($(obj).val());
                    });
                    window.localStorage.setItem("tags", values.join());
                });
                $('.sort-up').unbind('click').bind('click',function () {
                    $(this).parent().attr("data-order", 1);
                    var o = _this.getSearchParam();
                    $(this).css("color", "#fc7408");
                    $('.sort-down').css("color", "#333");
                    _this.showList($grid, o, true);
                    _this.scrollEvnet($grid, o);
                });
                $('.sort-down').unbind('click').bind('click',function () {
                    $(this).parent().attr("data-order", 0);
                    var o = _this.getSearchParam();
                    $(this).css("color", "#fc7408");
                    $('.sort-up').css("color", "#333");
                    _this.showList($grid, o, true);
                    _this.scrollEvnet($grid, o);
                });
            },
            mouseenterEvent: function ($dom) {
                $dom.find('.pic-main').unbind('mouseenter').bind('mouseenter', function () {
                    $('.grid-item').not($dom).find('.pic-background2').each(function () {
                        var paramsDom = $(this).parent();
                        paramsDom.find('.pic-background').hide();
                        paramsDom.find('.pic-background2').hide();
                    });
                    $dom.find('.pic-background').show();
                    $dom.find('.pic-background2').show();
                });
                $dom.find('.pic-background2').unbind('mouseenter').bind('mouseenter', function () {
                    $dom.find('.pic-background').show();
                    $(this).show();
                });
            },
            mouseleaveEvent: function ($dom) {
                $dom.find('.pic-background').unbind('mouseleave').bind('mouseleave', function () {
                    $dom.find('.pic-background').hide();
                    $dom.find('.pic-background2').hide();
                });
                $dom.find('.pic-background2').unbind('mouseleave').bind('mouseleave', function () {
                    $dom.find('.pic-background').hide();
                    $(this).hide();
                });
            },
            keepOnSearchStatus: function ($item, _id) {
                var _this = this;
                http.work('/ecTemplateMateriel/getprogress', {id: _id}, 'POST').then(function (res) {
                    if (res.flag == 'fail') {
                        Kit.alert2(res.errorMsg);
                        return;
                    } else {
                        if (res.data.progress == 100) {
                            //添加background 按倒background2
                            _this.addBackground($item, res.data);
                            //加入事件
                            $item.find('.pic-background').hide();
                            $item.find('.pic-background2').hide();
                            _this.mouseenterEvent($item);
                            _this.mouseleaveEvent($item);
                            //绑定 图片上的事件
                            _this.bindPicBtnEvent($item);
                        } else {
                            //加入 失败情况提示
                            if(res.data.materiel.createdStatus == 3){
                                var _html = _this.showTemplateForFailure(res.data.materiel,res.data.ext);
                                $item.find('.pic-background').empty().html(_html);
                                _this.bindRebuildEvent();
                                return false;
                            }
                            console.log("   progress :   " + res.data.progress);
                            $item.find('.pic-running span').html(res.data.progress);
                            if (_this.timeObj != null) {
                                clearTimeout(_this.timeObj);
                            }
                            _this.timeObj = setTimeout(function () {
                                if (window.location.hash.match("materialTemplate")) {
                                    _this.keepOnSearchStatus($item, _id);
                                }
                            }, 5000); //多久刷一次
                        }
                    }
                });
            },
            addBackground: function ($item, data) {
                var ext = data.ext, materiel = data.materiel || {};
                var background1 = '',
                    background2 = '';
                background1 += '<p>Creative Running</p><h5>' + I18N.getText('materialTemplate', 'viewStatusContains') + '' + (materiel.createdNum) + '' + I18N.getText('materialTemplate', 'viewStatusPictures') + '</h5>' +
                    '<ul><li>' + I18N.getText('materialTemplate', 'viewStatusRunning') + '：' + ext.running +
                    '</li><li>' + I18N.getText('materialTemplate', 'viewStatusPasued') + '：' + ext.paused + '</li><li>' + I18N.getText('materialTemplate', 'viewStatusStoped') + '：' + ext.deleted + '</li></ul></div>';
                //第二层
                background2 += '<div class="pic-background2"><span class="pic-view"><i class="glyphicon glyphicon-eye-open"></i>View More</span><span class="pic-pic"><i class="glyphicon glyphicon-cog"></i>' +
                    '<i class="font-icon font-icon-copy"></i>' +
                    '<i class="font-icon font-icon-del0"></i></span></div>';
                //加入 状态图标
                background2 += '<div data-show="false" class="pic-right"><img src="imgs/nouse.png"></div>';
                $item.find('.pic-background').empty().html(background1);
                $item.find('div.pic-right').remove();
                $item.append(background2);
            }
            /**
             * filter method
             */
            ,
            initFilter: function () {
                var _this = this;
                http.work('/ecMaterielCategory/supportMaterielFilter', {}, 'POST').then(function (res) {
                    if (res.flag == 'fail') {
                        Kit.alert2(res.errorMsg);
                        return;
                    } else {
                        $.each(res.data, function (i, obj) {
                            var _html = _this.generatHtml(obj);
                            var name = "#filter div[name='" + obj.categoryType + "'] .filter-body";
                            $(name).empty().append(_html);
                        });
                        _this.festivalBtnEvent();
                    }
                });
            },
            generatHtml: function(obj) {
                var _this = this,
                    _html = "";
                $.each(obj.children, function(j, o) {
                    if(o.categoryType == "festival"){
                        _html += '<input type="checkbox"  id="' + o.categoryType  + '-all" class="form-input" data-flag="1"  ' +
                            'data-type="' + obj.categoryType + '" name="' + o.categoryName + '"                                                                         value="' + o.id + '">';
                        _html += ' <label for="'  + o.categoryType  + '-all"><span class="checkbox-mark"></span>' + o.categoryName;
                        _html += '<span class="checkbox-text">[ detail<span class="sort-down glyphicon glyphicon-chevron-down"></span> ]</span></label>';
                        var festivalHtml = _this.generatHtml(o);
                        var name = "#filter div[name="+o.categoryType+"] .filter-body";
                        $(name).empty().append(festivalHtml);
                    }else if( obj.categoryType == "creativeType"){
                        if(o.categoryType == "adCarousel"){
                            _html = _this.addFilterAllTemp(_html);
                        }
                        _html += '<input type="radio"  id="' + o.categoryType  + '-all" class="form-input" data-flag="1"  ' +
                            'data-type="' + obj.categoryType + '" name="creativeType-radio"  value="' + o.id + '">';
                        _html += ' <label for="'  + o.categoryType  + '-all"><span class="radio-dot"></span>' + o.categoryName;
                        _html += '<span class="checkbox-text">[ detail<span class="sort-down glyphicon glyphicon-chevron-down"></span> ]</span></label>';
                        var festivalHtml = _this.generatHtml(o);
                        var name = "#filter div[name="+o.categoryType+"] .filter-body";
                        $(name).empty().append(festivalHtml);
                    }else{
                        _html = _this.addFilterCheckBoxTemp(_html,obj,o,j);
                    }
                });
                return _html;
            },
            addFilterCheckBoxTemp:function(_html,obj,o,j){
                if(obj.categoryType == "creativeStatus"){
                    _html += '<input type="checkbox"  id="' + (obj.categoryType + j) + '" class="form-input" data-flag="0"'
                    _html += 'data-type="' + o.categoryType + '" name="' + o.categoryName + '"  value="' + o.id + '">';
                }else{
                    _html += '<input type="checkbox"  id="' + (obj.categoryType + j) + '" class="form-input" data-flag="1"'
                    _html += 'data-type="' + obj.categoryType + '" name="' + o.categoryName + '"  value="' + o.id + '">';
                }
                _html += ' <label for="' + (obj.categoryType + j) + '"><span class="checkbox-mark"></span>' + o.categoryName;
                _html += '</label>';
                return _html;
            },
            addFilterAllTemp:function(_html){
                _html += '<input type="radio" id="creativeType-all" class="form-input" data-flag="1"' +
                    'data-type="" name="creativeType-radio"  value="">';
                _html += ' <label for="creativeType-all"><span class="radio-dot"></span>'+ I18N.getText("materialTemplate","All") +'</label>';
                return _html;
            },
            festivalBtnEvent: function () {
                $('div[name=adTarget] .checkbox-text').click(function () {
                    $('div[name=festival]').toggle();
                });
                //点击节日全选与取消
                $('#festival-all').unbind('click').bind('click',function () {
                    if ($(this).prop("checked")) {
                        $('input[data-type=festival]').prop("checked", true);
                    } else {
                        $('input[data-type=festival]').prop("checked", false);
                    }
                });
                $('input[data-type=festival]').unbind('click').bind('click',function () {
                    var flag = true;
                    $('input[data-type=festival]').each(function (i, obj) {
                        flag = $(obj).prop("checked");
                        if (!flag) {
                            return false;
                        }
                    });
                    if (flag) {
                        $('#festival-all').prop("checked", true);
                    } else {
                        $('#festival-all').prop("checked", false);
                    }
                });
                //点击单选事件
                $('#creativeType-all').unbind('click').bind('click',function(){
                    //隐藏所有，去掉下面所有checkbox
                    // data-type adCarousel  data-type adLink
                    $('input[data-type=adCarousel]').prop("checked", false);
                    $('input[data-type=adLink]').prop("checked", false);
                    $('div[name=adCarousel]').hide();
                    $('div[name=adLink]').hide();
                });
                $('#adCarousel-all').click(function(){
                    $('div[name=adCarousel]').show();
                    $('div[name=adLink]').hide();
                    $('input[data-type=adLink]').prop("checked", false);
                });
                $('#adLink-all').click(function(){
                    $('div[name=adLink]').show();
                    $('div[name=adCarousel]').hide();
                    $('input[data-type=adCarousel]').prop("checked", false);
                });
            },
            getFilterData: function () {
                var tags = [];
                //加入feed modify by hermen 2016-8-1
                if( $("input[name=drop]").attr("data-val") != "0"){
                    tags.push({
                        id:  $("input[name=drop]").attr("data-val"),
                        name: $("input[name=drop]").val(),
                        type: "productFeed",
                        flag: 1
                    });
                }
                $('input[type=checkbox]:checked').each(function (i, obj) {
                    if ($(obj).attr("id") != "festival-all") {  //去掉 节日的那个值
                        var tag = {
                            id: $(obj).val(),
                            name: $(obj).attr("name"),
                            type: $(obj).attr("data-type"),
                            flag: $(obj).attr("data-flag")
                        }
                        tags.push(tag);
                    }
                });
                return tags;
            },
            setTags: function ($grid, tags) {
                var _this = this;
                var _html = '';
                $.each(tags, function (i, obj) {
                    _html += '<span class="deco-tag" spell-check="false" data-val="' + obj.id + '" data-type="'+obj.type +'"><span class="deco-close">×</span>';
                    _html += obj.name + '</span>';
                    if (i == 11) {
                        _html += '<div style="height: 10px;"></div>';
                    }
                });
                $('#picList .tags').empty().html(_html);
                //bind   close btn
                $('.deco-close').unbind('click').bind('click',function () {
                    var tagValue = $(this).parent().attr('data-val');
                    var typeValue = $(this).parent().attr('data-type');
                    $(this).parent().remove();
                    //清除 filter中 checkbox
                    $('input[type=checkbox]:checked').each(function (i, obj) {
                        if ($(obj).val() == tagValue) {
                            $(obj).removeAttr("checked");
                            //如果是节日的选项，去除掉节日前面的按钮
                            if ($(obj).attr("data-type") == "festival") {
                                $('#festival-all').removeAttr("checked");
                            }
                        }
                        var tag = {
                            id: $(obj).val(),
                            name: $(obj).attr("name"),
                            type: $(obj).attr("data-type"),
                            flag: $(obj).attr("data-flag")
                        }
                        tags.push(tag);
                    });
                    //清除tree drop
                    if(typeValue == "productFeed"){
                        $("input[name=drop]").attr("data-val","0");
                        $("input[name=drop]").val("全部Feed");
                    }
                    //重新查询
                    var param = _this.getSearchParam();
                    _this.showList($grid, param, true);
                    _this.scrollEvnet($grid, param);
                });
            },
            filterBtnEvent: function ($grid) {
                var _this = this;
                $('button.btn-primary').unbind('click').bind('click',function () {
                    $('#filter').addClass("hidden"); //searchDiv
                    $('.creatTempBtn-text').addClass("hidden");
                    $('.searchDiv').show();
                    $('div.creatTempBtn-btn').show();
                    $('#picList').show();
                    //get tag  显示
                    var tags = _this.getFilterData();
                    _this.setTags($grid, tags);
                    var tempParam = _this.getSearchParam();
                    _this.showList($grid, tempParam, true);
                    _this.scrollEvnet($grid, tempParam);
                });
                $('button[name=cancel]').unbind('click').bind('click',function () {
                    //还原用户操作，将所选的 checkbox cancel 还原到之前状态
                    var values = window.localStorage.getItem("tags");
                    var valueAttr = values.split(',');
                    $('input[type=checkbox]').prop("checked", false);
                    $.each(valueAttr, function (i, obj) {
                        $('input[value="' + obj + '"]').prop("checked", true);
                    });

                    $('#filter').addClass("hidden"); //searchDiv
                    $('.creatTempBtn-text').addClass("hidden");
                    $('.searchDiv').show();
                    $('div.creatTempBtn-btn').show();
                    $('#picList').show();
                });
            }

            /**
             *   view more dialog
             */
            ,
            bindPicBtnEvent: function ($item) {
                var _this = this;
                $item.find('.pic-view').unbind('click').bind('click',function () {
                    $('#picDetail').modal({backdrop: 'static', keyboard: false});
                    _this.showDetail($item.attr('data-id'));
                    _this.bindReplaceBtnEvent($item.attr('data-id'));
                });
                $item.find('.pic-pic .font-icon-del0').unbind('click').bind('click',function () {
                    showConfirm({
                        title:I18N.getText('materialTemplate', 'deleteTitle'),
                        content: I18N.getText('materialTemplate', 'alertCheckDeleteMaterial'),
                        btnOK:I18N.getText('materialTemplate', 'Confirm'),
                        btnCANCEL:I18N.getText('materialTemplate', 'Cancel'),
                        onOK: function () { // 点击 “确认” 按钮回调函数
                            _this.deleteItem($item);
                        },
                        onCancel: function () { // 点击 “取消” 或者x 按钮回调函数
                            console.log(I18N.getText('materialTemplate', 'Cancel'));
                        }
                    });
                    //
                });
            },
            bindReplaceBtnEvent: function (id) {
                var _this = this;
                $("button[name=replace-btn]").unbind('click').bind('click', function () {
                    _this.showDetail(id);
                });
            },
            showDetail: function (_id) {
                var _this = this;
                http.work('/ecTemplateMateriel/viewMore', {id: Number(_id)}, 'POST').then(function (res) {
                    if (res.flag == 'fail') {
                        Kit.alert2(res.errorMsg);
                        return;
                    } else {
                        $('#picDetail-list').empty();
                        $('#picDetail').find('.tag').empty();
                        var materiel = res.data.materiel;
                        if(materiel != undefined){
                            $('#picDetail').find('.name').html(materiel.name);
                            $('#picDetail').find('label[name=updateTime]').html(moment(materiel.updateTime).format("YYYY-MM-DD hh:mm:ss"));
                            $('#picDetail').find('label[name=feedName]').html(materiel.productFeedName);
                            $('#picDetail').find('label[name=successNums]').html((Math.round(materiel.createdNum / materiel.productCount * 10000) / 100)+'%');

                            $('#picDetail').find('label[name=feedNums]').html(materiel.createdNum);
                            $('#picDetail').find('label[name=feedCount]').html(materiel.productCount);
                            $('#picDetail').find('label[name=noUseNums]').html(materiel.productCount - materiel.createdNum);
                            //set detail tag
                            _this.setDetailTags(res.data.tags);

                            //set 图片
                            _this.setDetailPices(materiel.width, res.data.feedList);
                        }
                    }
                });
            },
            deleteItem: function ($item) {
                http.work('/ecTemplateMateriel/delete', {id: Number($item.attr('data-id'))}, 'POST').then(function (res) {
                    if (res.flag == 'fail') {
                        Kit.alert2(res.errorMsg);
                        return;
                    } else {
                        //删除成功
                        Kit.alert_success(I18N.getText('materialTemplate', 'alertDeleteSuccess'));
                        //刷新数量
                        var total = $('.temp-total>span').html();
                        if(total != ""){
                            $('.temp-total>span').html( Number(total) - 1);
                        }
                        $item.remove();
                    }
                });
            },
            setDetailTags: function (tags) {
                var html = "";
                $.each(tags, function (i, obj) {
                    html += '<span class="view-tag">' + obj.tagName + '</span>'
                });
                $('#picDetail').find('.tag').html(html);
            },
            setDetailPices: function (width, feedList) {
                var _html = "";
                $.each(feedList, function (i, obj) {
                    if (width > 800) {
                        //双人图
                        _html += '<div class=""><img src="' + obj.image_link + '"></div>';
                    } else {
                        _html += '<div class=""><img src="' + obj.image_link + '"></div>';
                    }
                });
                $('#picDetail-list').append(_html);
            },
            events: function () {
                $('#picList').off('click', 'i.font-icon-copy').on('click', 'i.font-icon-copy', $.proxy(this.enterCopy, this));
                $('#picList').off('click', 'i.glyphicon-cog').on('click', 'i.glyphicon-cog', $.proxy(this.enterEdit, this));
            },
            /**
             * [enterCopy 进入copy页面]
             * @param  {[type]} e [description]
             * @return {[type]}   [description]
             */
            enterCopy: function (e) {
                var id = $(e.currentTarget).closest('.grid-item').data('id');
                if (id) {
                    window.location.hash = '#!materialCopy?type=copy&id=' + id;
                }
            },
            /**
             * { 进入编辑界面 }
             *
             * @param      {<type>}  e       { parameter_description }
             */
            enterEdit: function (e) {
                var id = $(e.currentTarget).closest('.grid-item').data('id');
                //加入状态标示  modify by hm 08-02
                var status = $(e.currentTarget).attr("data-status");
                if (id) {
                    window.location.hash = '#!materialCopy?type=edit&id=' + id +'&status=' + status;
                }
            }
            , checkUrl: function () {
                if (window.location.hash.match("materialTemplate")) {
                    return true;
                }
            }
            /**
             * 重构 显示模板列表
             */
            , checkIsNotSinglePicture: function (_html, _picBackground, picData) {
                var tempObj = {h: "", p: ""};
                if (picData.width > 800) {
                    //双人图
                    tempObj.h = '<div data-id="' + picData.id + '" class="grid-item grid-item-2"><img class="pic-top" src="imgs/pic-top-big.png" />';
                    tempObj.p = '<div class="pic-background grid-item-2">';
                } else {
                    //单人图
                    tempObj.h = '<div data-id="' + picData.id + '" class="grid-item"><img class="pic-top" src="imgs/pic-top.png" />';
                    tempObj.p = '<div class="pic-background">';
                }
                return tempObj;
            }
            , showTempLateForRunning: function (_html, obj,picData,ext) {
                _html += '<p>' + I18N.getText('materialTemplate', 'viewStatusRunning') + '</p><h5>'
                    + I18N.getText('materialTemplate', 'viewStatusContains') + '' + (picData.createdNum) + ''
                    + I18N.getText('materialTemplate', 'viewStatusPictures') + '</h5>' +
                    '<ul>' +
                    '<li>' + I18N.getText('materialTemplate', 'viewStatusRunning') + '：' + ext.running + '</li>'+
                    '</li>' +
                    '<li>' + I18N.getText('materialTemplate', 'viewStatusPasued') + '：' + ext.paused + '</li>'+
                    '</li>' +
                    '<li>' + I18N.getText('materialTemplate', 'viewStatusStoped') + '：' + ext.deleted + '</li>' +
                    '</ul>' +
                    '</div>';
                //第二层
                _html += '<div class="pic-background2"><span class="pic-view">' +
                    '<i class="glyphicon glyphicon-eye-open"></i>' + I18N.getText('materialTemplate', 'viewStatusViewMore') + '</span><span class="pic-pic">';
                if (obj.materiel && (obj.materiel.materielCode.indexOf('P') > 0 || obj.materiel.materielCode.indexOf('T') > 0)) {
                    _html += '<i data-status ="running" class="glyphicon glyphicon-cog"></i>';
                    _html += '<i class="font-icon font-icon-copy"></i>';
                }
                _html += '</span></div>';
                _html += '<div data-show="false" class="pic-right"><img src="imgs/running.png"></div>';
                return _html;
            }
            , showTemplateForNotUsed: function (_html,obj,picData,ext) {
                _html += '<p>' + I18N.getText('materialTemplate', 'viewStatusNotUserd') + '</p><h5>' + I18N.getText('materialTemplate', 'viewStatusContains') + '' + (picData.createdNum) + '' + I18N.getText('materialTemplate', 'viewStatusPictures') + '</h5>' +
                    '<ul><li>' + I18N.getText('materialTemplate', 'viewStatusRunning') + '：' + ext.running + '</li><li>' + I18N.getText('materialTemplate', 'viewStatusPasued') + '：'
                    + ext.paused + '</li><li>' + I18N.getText('materialTemplate', 'viewStatusStoped') + '：' + ext.deleted + '</li></ul></div>';
                //第二层
                _html += '<div class="pic-background2"><span class="pic-view">' +
                    '<i class="glyphicon glyphicon-eye-open"></i>' + I18N.getText('materialTemplate', 'viewStatusViewMore') + '</span><span class="pic-pic">';
                if (obj.materiel && (obj.materiel.materielCode.indexOf('P') > 0 || obj.materiel.materielCode.indexOf('T') > 0)) {
                    _html += '<i data-status ="notUsed" class="glyphicon glyphicon-cog"></i>'
                    _html += '<i class="font-icon font-icon-copy"></i>';
                }
                _html += '<i class="font-icon font-icon-del0"></i></span></div>';
                _html += '<div data-show="false" class="pic-right"><img src="imgs/nouse.png"></div>';
                return _html;
            }
            , showTemplateForGenerating: function (_html, obj) {
                var num = 0;
                if(obj != null){
                    num = obj.process;
                }
                //显示进度
                _html += '<div class="pic-running"><span>' + num + '</span>%...<h4>'
                    + I18N.getText('materialTemplate', 'picBackgroundFinished') + '</h4></div></div>'
                    + '<div data-show="true" class="pic-right">' + I18N.getText('materialTemplate', 'picBackgroundGenerating')
                    + '...</div>';
                return _html;
            }
            /**
             * 显示错误信息
             * @param _html
             * @param picData
             * @returns {string|*}
             */
            , showTemplateForFailure: function (picData,ext) {
                var _html = '<div class="pic-running"><span class="fail">'+I18N.getText('materialTemplate', 'BatchError')+'</span>' +
                    '<div data-id="'+picData.id+'" class="pic-btn"><i class="font-icon font-icon-recycle"></i>&nbsp;'+I18N.getText('materialTemplate', 'Regenerate')+'</div>';

                if (ext.running > 0 || ext.paused > 0) {
                   //存在运行的和暂停的 不能删除
                } else {
                    _html += '<div class="pic-delete"><i class="font-icon font-icon-del0"></i>&nbsp;'+I18N.getText('materialTemplate', 'Delete')+'</div>';
                }

                _html += '</div>';
                return _html;
            }
            /**
             * 已删除的模板显示信息
             * @param _html
             * @param obj
             * @param picData
             * @param ext
             * @returns {string|*}
             */
            , showTemplateForDelete: function (_html,obj,picData,ext) {
                _html += '<p>' + I18N.getText('materialTemplate', 'viewStatusStoped') + '</p><h5>' + I18N.getText('materialTemplate', 'viewStatusContains') + '' + (picData.createdNum) + '' + I18N.getText('materialTemplate', 'viewStatusPictures') + '</h5>' +
                    '<ul><li>' + I18N.getText('materialTemplate', 'viewStatusRunning') + '：' + ext.running + '</li><li>' + I18N.getText('materialTemplate', 'viewStatusPasued') + '：'
                    + ext.paused + '</li><li>' + I18N.getText('materialTemplate', 'viewStatusStoped') + '：' + ext.deleted + '</li></ul></div>';
                //第二层
                _html += '<div class="pic-background2"><span class="pic-view">' +
                    '<i class="glyphicon glyphicon-eye-open"></i>' + I18N.getText('materialTemplate', 'viewStatusViewMore') + '</span><span class="pic-pic">';
                //过滤早期模板
                if (obj.materiel && (obj.materiel.materielCode.indexOf('P') > 0 || obj.materiel.materielCode.indexOf('T') > 0)) {
                    _html += '<i class="glyphicon glyphicon-cog"></i>'
                    _html += '<i class="font-icon font-icon-copy"></i>';
                }
                _html += '<i class="font-icon font-icon-del0"></i></span></div>';
                _html += '<div data-show="false" class="pic-right"><img src="imgs/stop.png"></div>';
                return _html;
            }
            , showTemplateForPause: function (_html,obj,picData,ext) {
                _html += '<p>' + I18N.getText('materialTemplate', 'Pausing') + '</p><h5>' + I18N.getText('materialTemplate', 'viewStatusContains') + '' + (picData.createdNum) + '' + I18N.getText('materialTemplate', 'viewStatusPictures') + '</h5>' +
                    '<ul><li>' + I18N.getText('materialTemplate', 'viewStatusRunning') + '：' + ext.running + '</li><li>' + I18N.getText('materialTemplate', 'viewStatusPasued') + '：'
                    + ext.paused + '</li><li>' + I18N.getText('materialTemplate', 'viewStatusStoped') + '：' + ext.deleted + '</li></ul></div>';
                //第二层
                _html += '<div class="pic-background2"><span class="pic-view">' +
                    '<i class="glyphicon glyphicon-eye-open"></i>' + I18N.getText('materialTemplate', 'viewStatusViewMore') + '</span><span class="pic-pic">';
                if (obj.materiel && (obj.materiel.materielCode.indexOf('P') > 0 || obj.materiel.materielCode.indexOf('T') > 0)) {
                    _html += '<i class="glyphicon glyphicon-cog"></i>';
                    _html += '<i class="font-icon font-icon-copy"></i>';
                }
                _html += '<div data-show="false" class="pic-right"><img src="imgs/pause.png"></div>';
                return _html;
            }
            ,bindRebuildEvent:function(){
                var _this = this;
                $('#masonryDom').find('.pic-btn').unbind("click").bind("click",function(obj){
                    var id = $(this).attr("data-id");
                    _this.rebuild(id,$(this));
                });
                $('#masonryDom').find('.pic-delete').unbind("click").click(function () {
                    var $item = $(this).closest('.grid-item');
                    showConfirm({
                        title:I18N.getText('materialTemplate', 'deleteTitle'),
                        content: I18N.getText('materialTemplate', 'alertCheckDeleteMaterial'),
                        btnOK:I18N.getText('materialTemplate', 'Confirm'),
                        btnCANCEL:I18N.getText('materialTemplate', 'Cancel'),
                        onOK: function () { // 点击 “确认” 按钮回调函数
                            _this.deleteItem($item);
                        },
                        onCancel: function () { // 点击 “取消” 或者x 按钮回调函数
                            console.log(I18N.getText('materialTemplate', 'Cancel'));
                        }
                    });
                    //
                });
            }
            /**
             * 重新生成模板
             * @param id
             * @param $dom   $(.pic-btn)
             */
            ,rebuild:function(id,$dom){
                var self = this;
                //ecTemplateMateriel/reBuild
                http.work('/ecTemplateMateriel/reBuild', {id:id}, 'POST').then(function (res) {
                    if (res.flag == 'fail') {
                        Kit.alert2(res.errorMsg);
                        return;
                    } else {
                        if(res.data == true){
                            //显示进行中的页面
                            var $item = $dom.closest('.grid-item');
                            self.addRunningHtml($item);
                            self.keepOnSearchStatus($item, id);
                        }
                    }
                });

            }
            /**
             *  替换如running提示语
             * @param $item
             */
            ,addRunningHtml:function($item){
                var _html = "";
                _html = this.showTemplateForGenerating(_html);
                $item.find('.pic-background').empty().html(_html);
                //$item.append('<div data-show="false" class="pic-right"><img src="imgs/pause.png"></div>');
            }
            /**
             * 初始化树状下拉菜单
             */
            // I18N.getText('materialTemplate', 'deleteTitle')
            ,initTreeDrop:function(){
                var productArr = [{text:I18N.getText('materialTemplate', 'All') + " Feed",val:"0"}];
                http.work('/productmanage/findPmAndFeedAllByOrgId', {}, 'POST').then(function (res) {
                    $(res.data).each(function(i,obj){
                        var feedArry=[];

                        // 如果没有feed的话 不能选择产品
                        if(obj.feedWeList && obj.feedWeList.length > 0) {
                            $(obj.feedWeList).each(function (j, subObj) {
                                feedArry.push({
                                    text: subObj.feedName,
                                    val: subObj.id
                                });
                            });
                            var o = {
                                text: obj.prodName,
                                val: obj.id
                            }
                            if (feedArry.length != 0) {
                                o.sub = feedArry
                            }
                            productArr.push(o);
                        } else {
                            var o = {
                                text: obj.prodName,
                                val: obj.id,
                                disable:true
                            }
                            if (feedArry.length != 0) {
                                o.sub = feedArry
                            }
                            productArr.push(o);
                        }
                    });

                    //randen tree drop
                    $("div.ndp-drop-wrapper[name=tree-drop]").drop({
                        data:productArr,
                        caret:"glyphicon-menu-right"
                    }).on("ITEM_CLICK",function(e){//下拉菜单一个选项被点击了
                        //添加到标签中
                    }).val(I18N.getText('materialTemplate', 'All') + " Feed"); //设置 显示在input 里面的值
                    $("input[name=drop]").attr("data-val","0");
                });
            }
        }
        return materialTemplates;
    });
